
package org.privat24.api.misc;

import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;


public class SignatureUtil {
    

    public static String calculateSignature(String pass, String data) {
        String result = new String();
        try {
            result = sha1(md5(data + pass), "UTF-8");
        } catch (NoSuchAlgorithmException ex){
            System.err.println(ex);
        } catch (UnsupportedEncodingException ex) {
            System.err.println(ex);
        }
        return result;
    }

    private static String sha1(String Param, String Encode) throws NoSuchAlgorithmException, UnsupportedEncodingException {
        MessageDigest sha = MessageDigest.getInstance("SHA-1");
        sha.reset();
        sha.update(Param.getBytes(Encode), 0, Param.length());
        byte[] sha1hash = sha.digest();
        return bytesToHexStr(sha1hash);
    }

    private static String md5(String input) throws NoSuchAlgorithmException {
        String md5;
        StringBuilder code = new StringBuilder();
        java.security.MessageDigest messageDigest = java.security.MessageDigest.getInstance("MD5");
        byte bytes[] = input.getBytes();
        byte digest[] = messageDigest.digest(bytes);
        for (int i = 0; i < digest.length; ++i) {
            code.append(Integer.toHexString(0x0100 + (digest[i] & 0x00FF)).substring(1));
        }
        md5 = code.toString();
        return md5;
    }

    private static String bytesToHexStr(byte[] raw) {
        char[] kDigits = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'};
        int length = raw.length;
        char[] hex = new char[length * 2];
        for (int i = 0; i < length; i++) {
            int value = (raw[i] + 256) % 256;
            int highIndex = value >> 4;
            int lowIndex = value & 0x0f;
            hex[i * 2 + 0] = kDigits[highIndex];
            hex[i * 2 + 1] = kDigits[lowIndex];
        }
        return new String(hex);
    }
}
